package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.android.barcodescandemo.ScannerInerface;
import com.example.administrator.k3xiangmu.adapter.Diaobo2Adapter;
import com.example.administrator.k3xiangmu.adapter.Saomiao2Adapter;
import com.example.administrator.k3xiangmu.entity.Diaobo2Entity;
import com.example.administrator.k3xiangmu.entity.Saomiao2Entity;
import com.uuzuche.lib_zxing.activity.CaptureActivity;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Diaobo2Activity extends AppCompatActivity {
    private Toolbar toolbar;
    ListView lv;
    Diaobo2Adapter adapter;
    ProgressDialog dialog;

    List<Diaobo2Entity> list = new ArrayList<>();
    private String s = "";
    private String no = "";
    private String biller = "";
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    ScannerInerface Controll = new ScannerInerface(this);
    private Button bt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diaobo2);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setTool();
        dialog = new ProgressDialog(this);
        //
        Controll.open();
        Controll.setOutputMode(1);//使用广播模式
        mFilter = new IntentFilter("android.intent.action.SCANRESULT");

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 此处获取扫描结果信息
                final String scanResult = intent.getStringExtra("value").split("\\[")[0];


                for (int i = 0; i < list.size(); i++) {

                    if (list.get(i).getId().equals(scanResult)&&list.get(i).getStatus()==2) {
                        Toast.makeText(Diaobo2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                        return;
                    }else if(list.get(i).getId().equals(scanResult)){
                        int a = list.get(i).getYs();
                        if (list.get(i).getFqty() > a) {
                            list.get(i).setYs(++a);
                            if(list.get(i).getFqty()==a){
                                list.get(i).setStatus(2);
                            }
                        }

                        adapter.notifyDataSetChanged();
                        return;
                    }

                }
                Toast.makeText(Diaobo2Activity.this, "找不到该条码", Toast.LENGTH_LONG).show();

            }
        };
        s = getIntent().getStringExtra("id");
        lv = (ListView) findViewById(R.id.lv);
        adapter = new Diaobo2Adapter(list, this);
        lv.setAdapter(adapter);
        bt = (Button) findViewById(R.id.tj);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getStatus() == 0) {
                        Toast.makeText(Diaobo2Activity.this, "有单子未扫描", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                submit();
            }
        });
        getData();

    }
    private void submit() {
        dialog.show();
        UpdateTextTask3 updateTextTask = new UpdateTextTask3(Diaobo2Activity.this);
        updateTextTask.execute();
    }

    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("调拨单详情");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                String msg = "";
//                switch (item.getItemId()) {
//                    case R.id.action_sm:
//                        msg += "Click edit";
//                        break;
//
//                }
//
//                if (!msg.equals("")) {
//                    Toast.makeText(Diaobo2Activity.this, msg, Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(Diaobo2Activity.this, CaptureActivity.class);
//                    startActivityForResult(intent, 111);
//
//                }
//                return true;
//
//            }
//        });
    }
    private void update() {
        UpdateTextTask3 updateTextTask = new UpdateTextTask3(this);
        updateTextTask.execute();
    }

    private void getData() {
        dialog.show();
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "b");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            adapter.notifyDataSetChanged();
            //     Log.i("ss", list.get(1).getId() + "+++++++++++++++");
            dialog.dismiss();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "c");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            Toast.makeText(Diaobo2Activity.this, "成功", Toast.LENGTH_LONG).show();
            finish();
            ;

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {
            list.clear();
            String sql = "select a.fqty ,b.FName,b.fnumber from ICStockBillentry a inner join t_icitem b on a.fitemid=b.fitemid where FInterID="+s+"";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                Diaobo2Entity entity = new Diaobo2Entity();
                entity.setFName(rs.getString("FName"));
                //int i=Integer.parseInt(rs.getString("fqty"));
//                double i=Double.parseDouble(rs.getString("fqty"));
//                Log.i("sss",i+"+");
                entity.setFqty((int)Double.parseDouble(rs.getString("fqty")));
                entity.setId(rs.getString("fnumber"));
                list.add(entity);


            }


            rs.close();
            stmt.close();
        } catch (SQLException e) {

           Log.i("sss",e.toString());

        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    public void testConnection3(Connection con) throws java.sql.SQLException {

        try {

            String sql = "update ICStockBill set fcheckerid=16394 where FInterId='" + s + "'";

            Statement stmt = con.createStatement();// 创建Statement
            stmt.executeUpdate(sql);


            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    protected void onPause() {
        this.unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mReceiver = null;
        mFilter = null;

        Controll.close();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);//加载menu文件到布局
        return true;
    }

    class UpdateTextTask4 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask4(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection4(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "a");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            Toast.makeText(Diaobo2Activity.this, "提交成功", Toast.LENGTH_LONG).show();
            finish();


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection4(Connection con) throws java.sql.SQLException {
        CallableStatement callStmt = null;
        Statement stmt2 =null;
        try {
            callStmt = con.prepareCall("{call [x_xlh] (?,?)}");
            stmt2=con.createStatement();
            callStmt.setString(1, no);
            callStmt.setString(2, biller);

            callStmt.execute();
            //callStmt.executeUpdate("update t_BOS200000001 set fmulticheckstatus=16 where fbillno="+no+"");
            int r=stmt2.executeUpdate("update t_BOS200000001 set fmulticheckstatus=16 where fbillno='"+no+"'");
            Log.i("qqq",r+"++++++++++++");

        } catch (SQLException e) {
            Log.i("qqq",e.toString()+"++++++++++++");

        } finally {
            if (null != callStmt) {
                callStmt.close();
            }
            if(null != stmt2){
                stmt2.close();
            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
}
